import cv2 as cv
import face_recognition as fr

from face_detect.face_to_detect import detectE

stored_face_encodings = []


def recognize(face):
    match = fr.compare_faces(stored_face_encodings, face)
    try:
        face_id = match.index(True)
        return face_id
    except ValueError:
        return None


def paint(frame, location, name):
    (_, left, bottom, right) = location
    cv.rectangle(frame, (left, bottom - 25),
                 (right, bottom), (0, 0, 255), cv.FILLED)
    font = cv.FONT_HERSHEY_DUPLEX
    cv.putText(frame, name, (left-110, bottom - 6),
               font, 0.5, (255, 255, 255), 1)


def recordAndDisplay(frame, model="hog"):
    face_locations = detectE(frame, model=model)
    face_encodings = fr.face_encodings(frame, face_locations)
    for (index, face) in enumerate(face_encodings):
        identifier = recognize(face)
        if identifier == None:
            stored_face_encodings.append(face)
            print("Record a new person")
        else:
            paint(frame, face_locations[index], "My name" + str(identifier))

    cv.imshow('Capture - Face detection', frame)


camera_device = 0

# -- 2. Read the video stream
cap = cv.VideoCapture(camera_device)
if not cap.isOpened:
    print('--(!)Error opening video capture')
    exit(0)

while True:
    ret, frame = cap.read()
    if frame is None:
        print('--(!) No captured frame -- Break!')
        break

    recordAndDisplay(frame)

    if cv.waitKey(10) == 27:
        break
